package com.stylefeng.guns.rest.modular.wz.api.v2;


import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.config.properties.JwtProperties;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnWzAdv;
import com.stylefeng.guns.rest.enums.EnWzUser;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.AsyncService;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzAdvServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzAnswerServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzUserQuestionnaireServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 分享广告表
 */
@RestController
@RequestMapping("/wz/api/v2/adv/")
public class WzAdvApiV2 extends ApiBaseController {

    @Autowired
    private WzQuestionMapper questionMapper;
    @Autowired
    private WzAnswerMapper answerMapper;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzUserInfoMapper userInfoMapper;
    @Autowired
    private WzCouponMapper couponMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzUserQuestionnaireMapper userQuestionnaireMapper;
    @Autowired
    private WzUserFinanceRecordMapper userFinanceRecordMapper;
    @Autowired
    private WzAdvServiceImpl advService;
    @Autowired
    private WzUserAdvRecordMapper userAdvRecordMapper;
    @Autowired
    private WzQuestionnaireMapper questionnaireMapper;
    @Autowired
    private WzUserAdvCollectionMapper userAdvCollectionMapper;
    @Autowired
    private WzAdvUserMapper advUserMapper;
    @Autowired
    private WzAdvCommentMapper advCommentMapper;
    @Autowired
    private PfOpenCityMapper openCityMapper;
    @Autowired
    private PfReportMapper reportMapper;
    @Autowired
    private PfFinanceRecordMapper pfFinanceRecordMapper;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private AsyncService asyncService;
    @Autowired
    private WzUserQuestionnaireServiceImpl userQuestionnaireService;
    @Autowired
    private WzAnswerServiceImpl answerService;
    @Autowired
    private WzRedpacketCommentMapper redpacketCommentMapper;
    @Autowired
    private WzRedpacketCommentLikeMapper redpacketCommentLikeMapper;
    @Autowired
    private WzAdvShareMapper advShareMapper;
    @Autowired
    private WzUserFixedInfoMapper userFixedInfoMapper;
    @Autowired
    private WzShareMapper shareMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private WzRedpacketMapper redpacketMapper;

    /**
     * 用户红包领取记录
     */
    @PostMapping("userAdvRecord")
    public Res userAdvRecord(){
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        String sql = "adv_id As advId";
        List<Map<String,Object>>  userAdvRecords = userAdvRecordMapper.selectMaps(new EntityWrapper<WzUserAdvRecord>().setSqlSelect(sql).eq("subtype", EnWzAdv.SUBTYPE_user_redPacket.getIndex()).eq("user_code",userCode).eq("status", EnWzUser.User_Adv_Record_Status_Unexpired.getIndex()));
        return Res.success(userAdvRecords);
    }

    /**
     * 红包领钱
     */
//    @PostMapping("reward")
//    public Res reward(@RequestBody ParamMap paramMap){
//        Long advId = paramMap.getLongMisValid("advId");
//        String adCode = paramMap.getStrValid("adCode");
//        WzAdv adv = advMapper.selectById(advId);
//        if(StringUtils.isNotBlank(adCode)){
//            boolean f = cacheService.city(adCode + ","+adv.getScreenCity());
//            if(!f){
//                return Res.fail("所在地区无法领钱!");
//            }
//        }
//        Long userCode = jwtTokenUtil.getUserCodeFromToken();
//        String advUserId = paramMap.getStrValid("advUserId");//广告问卷id
//        //判断广告失效
//        if(adv.getStatus() == EnWzAdv.STATUS_DOWN.getIndex() || new Date().after(adv.getEndTime()) || adv.getStatus() == EnWzAdv.STATUS_RELEASE_yes.getIndex()){
//            //删除广告用户
//            advUserMapper.delete(new EntityWrapper<WzAdvUser>().eq("adv_id",adv.getAdvId()));
//            return Res.fail(BizExceptionEnum.ADV_SHIXIAO);
//        }
//        //用户发布信息数量筛选
//        if((adv.getPushNumber() + 1) > adv.getTotalNumber()){
//            //删除广告用户
//            advUserMapper.delete(new EntityWrapper<WzAdvUser>().eq("adv_id",adv.getAdvId()));
//            return Res.fail(BizExceptionEnum.ADV_SHIXIAO);
//        }
//        //判断是否已领钱
//        int c = userAdvRecordMapper.selectCount(new EntityWrapper<WzUserAdvRecord>().eq("user_code",userCode).eq("adv_user_id",advUserId));
//        if(c > 0){
//            return Res.fail(BizExceptionEnum.ADV_SHIXIAO);
//        }
//        WzAdvUser advUsers = advUserMapper.selectById(Long.parseLong(advUserId));
//        adv.setPushNumber(adv.getPushNumber() + 1);
//        if(adv.getPushNumber() >= adv.getTotalNumber()){
//            adv.setStatus(EnWzAdv.STATUS_RELEASE_yes.getIndex());
//        }
//        //业务处理
//        Res res = advService.userAdvReward(paramMap,adv,userCode,advUsers);
//        return res;
//    }

    /**
     * 分享详情
     */
    @PostMapping("shareDetail")
    public Res shareDetail(@RequestBody ParamMap paramMap){
        String androidVersion = paramMap.getStrValid("androidVersion");
        String iosVersion = paramMap.getStrValid("iosVersion");
        String adCode = paramMap.getStrValid("adCode");
        boolean rr = true;
        if(!StringUtils.isBlankStr(iosVersion)){
            int ios = Integer.parseInt(iosVersion.substring(0,1))*100 + Integer.parseInt(iosVersion.substring(2,3))*10 + Integer.parseInt(iosVersion.substring(4,5));
            if(ios >= Integer.parseInt(Consts.iosVersion)){
                rr = false;
            }
        }
        if(!StringUtils.isBlankStr(androidVersion)){
            int a = Integer.parseInt(androidVersion);
            if(a >= Integer.parseInt(Consts.androidVersion)){
                rr = false;
            }
        }
        if(rr){
            return Res.fail("版本太低无法分享，请更新!");
        }

        Long advId = paramMap.getLongMisValid("advId");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzAdv userAdv = advMapper.selectById(advId);
        //位置判断
        if(adCode.length() != 6){
            return Res.fail(BizExceptionEnum.RES_Ad_Code_Abnormal);
        }
        boolean f = advService.adCodeCheck(adCode,userAdv.getScreenCity());
        if(!f){
            return Res.fail("所在地区无法领钱!");
        }

        paramMap.put("avatarUrl",userAdv.getAvatarUrl());//发布人头像
        paramMap.put("nickName",userAdv.getNickName());//发布人昵称
        paramMap.put("shareReward",userAdv.getShareReward());//奖金总额
        if(userAdv.getShareAverageReward() == 0){
            paramMap.put("shareUserNumber",0);//可参与分享总人数
        }else{
            paramMap.put("shareUserNumber",userAdv.getShareReward()/userAdv.getShareAverageReward());//可参与分享总人数
        }
        if(userAdv.getIsShareSettlement() == 1){
            paramMap.put("status",7);//状态:待分享
        }else{
            paramMap.put("status",userAdv.getStatus());//状态
        }
        paramMap.put("endTime",userAdv.getEndTime());//结束时间
        paramMap.put("title",userAdv.getTitle());//标题
        paramMap.put("coverUrl",userAdv.getCoverUrl());//封面
        paramMap.put("partitionReward",0);//瓜分金额
//        int partitionShares = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("adv_id",advId).ne("partition_reward",0));
        paramMap.put("partitionNumber",0);//参与瓜分人数
        List<Map<String, Object>> totalProfit = advShareMapper.selectMaps(Condition.create().setSqlSelect("sum(share_number) As totalshareNumber").eq("adv_id",advId));
        if(totalProfit.get(0) == null){
            paramMap.put("totalshareNumber",0);//总点击数
        }else{
            paramMap.put("totalshareNumber",totalProfit.get(0).get("totalshareNumber").toString());//总点击数
        }
        String sql = "avatar_url As avatarUrl";
        List<Map<String,Object>> effectivecClickList = shareMapper.selectMapsPage(new Page<>(1,3),new EntityWrapper<WzShare>().setSqlSelect(sql).eq("target_id",advId).eq("user_code",userCode).orderBy("create_time",false));
        if(effectivecClickList.size() > 0){
            paramMap.put("effectivecClickList",effectivecClickList);//有效点击好友列表
        }else{
            effectivecClickList = new ArrayList<>();
            paramMap.put("effectivecClickList",effectivecClickList);//有效点击好友列表
        }
        List<WzAdvShare> myAdvShares = advShareMapper.selectList(new EntityWrapper<WzAdvShare>().eq("adv_id",advId).eq("user_code",userCode));
        if(myAdvShares.size() > 0){
            paramMap.put("myPartitionReward",myAdvShares.get(0).getPartitionReward());//自己的瓜分收益
            paramMap.put("effectivecClicks",myAdvShares.get(0).getShareNumber());//有效点击数
            if(myAdvShares.get(0).getShareReward() != 0 && myAdvShares.get(0).getShareReward() != -1){
                paramMap.put("myShareReward",myAdvShares.get(0).getShareReward());//分享收益
            }else{
                paramMap.put("myShareReward",0);//分享收益
            }
            if(userAdv != null){
                if(userAdv.getIsShareSettlement() == 0){
                    paramMap.put("status",myAdvShares.get(0).getStatus());//状态
                }
            }
        }else{
            paramMap.put("effectivecClicks",0);//有效点击数
            paramMap.put("myShareReward",0);//分享收益
            paramMap.put("myPartitionReward",0);//自己的瓜分收益
        }
        int advShares = 0;
        List<Map<String,Object>> shareNumberList = new ArrayList<>();
        if(userAdv != null){
            advShares = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("adv_id",advId));
            shareNumberList = advShareMapper.selectMapsPage(new Page<>(1,3),new EntityWrapper<WzAdvShare>().eq("adv_id",advId).orderBy("share_number",false));
        }
        paramMap.put("shareNumber",advShares);//参与分享人数
        if(shareNumberList.size() > 0){
            paramMap.put("shareNumberList",shareNumberList);//参与分享用户列表
        }else{
            shareNumberList = new ArrayList<>();
            paramMap.put("shareNumberList",shareNumberList);//参与分享用户列表
        }
        paramMap.put("advPartitionList",new ArrayList<>());//参与瓜分用户列表
        if(Consts.dev.equals("true")){
            paramMap.put("rewardShareLink", ""+ Consts.Adv_Share_Api_Domain_Test+"/wz/wzShare/share?advId="+advId+"&type=1&userCode="+userCode.toString()+"&screenCity="+userAdv.getScreenCity());
            if(userAdv.getSubtype() == EnWzAdv.SUBTYPE_Share_MapAdv.getIndex()){
                paramMap.put("rewardShareLink", ""+ Consts.Adv_Share_Api_Domain_Test+"/wz/wzShare/share?advId="+userAdv.getShareLink().substring(28,47)+"&type=1&userCode="+userCode.toString()+"");
            }
        }else{
            paramMap.put("rewardShareLink", ""+ Consts.Adv_Share_Api_Domain+"/wz/wzShare/share?advId="+advId+"&type=1&userCode="+userCode.toString()+"&screenCity="+userAdv.getScreenCity());
            if(userAdv.getSubtype() == EnWzAdv.SUBTYPE_Share_MapAdv.getIndex()){
                paramMap.put("rewardShareLink", ""+ Consts.Adv_Share_Api_Domain+"/wz/wzShare/share?advId="+userAdv.getShareLink().substring(28,47)+"&type=1&userCode="+userCode.toString()+"");
            }
        }
        int count = 0;
        if(userAdv != null){
            count = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("adv_id",advId).eq("user_code",userCode).ne("share_reward",0));
        }
        if(count > 0){
            paramMap.put("isShare", 1);
        }else{
            paramMap.put("isShare", 0);
        }
        if(userAdv != null) {
            if (StringUtils.isNotBlank(userAdv.getShareDesc())) {
                paramMap.put("shareDesc", userAdv.getShareDesc());
            } else {
                paramMap.put("shareDesc", Consts.shareDesc);
            }
        }
        return Res.success(paramMap);
    }

    /**
     * 有效点击好友
     */
    @PostMapping("effectivecClickList")
    public Res effectivecClickList(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long advId = paramMap.getLongMisValid("advId");
        Long userCode = paramMap.getLongValid("userCode");
        if(userCode == null){
            userCode = jwtTokenUtil.getUserCodeFromToken();
        }
        String effectivecClickListSql = "avatar_url As avatarUrl,nick_name As nickName,create_time As createTime";
        List<Map<String,Object>> effectivecClickList = shareMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzShare>().setSqlSelect(effectivecClickListSql).eq("target_id",advId).eq("user_code",userCode).orderBy("create_time",false));
        return Res.success(paramMap.data(effectivecClickList));
    }

    /**
     * 参与瓜分用户列表
     */
//    @PostMapping("advPartitionList")
//    public Res advPartitionList(@RequestBody ParamMap paramMap){
//        int pageNum = paramMap.getIntMisValid("pageNum");
//        int pageSize = paramMap.getIntMisValid("pageSize");
//        Long advId = paramMap.getLongMisValid("advId");
//        List<Map<String,Object>> advShareList = advShareMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzAdvShare>().eq("adv_id",advId).ne("partition_reward",0).orderBy("create_time",false));
//        return Res.success(paramMap.data(advShareList));
//    }

    /**
     * 参与分享用户列表
     */
    @PostMapping("advShareList")
    public Res advShareList(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long advId = paramMap.getLongMisValid("advId");
        WzAdv adv = advMapper.selectById(advId);
        List<Map<String,Object>> advShareList = new ArrayList<>();
        if(adv != null){
            if(adv.getShareAverageReward() == 0){
                advShareList = advShareMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzAdvShare>().eq("adv_id",advId).orderBy("share_number",false));
            }else{
                advShareList = advShareMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzAdvShare>().eq("adv_id",advId).ne("share_reward",0).orderBy("share_number",false));
            }
            for(Map<String,Object> advShare:advShareList){
                if(advShare.get("shareReward").toString().equals("-1")){
                    advShare.put("shareReward","0");
                }
            }
        }
        return Res.success(paramMap.data(advShareList));
    }

    /**
     * 收益进行中列表
     */
    @PostMapping("advShareIngList")
    public Res advShareIngList(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        String switchAdCode = paramMap.getStrValid("switchAdCode");
        if(StringUtils.isBlank(switchAdCode)){
            switchAdCode = paramMap.getStrMisValid("adCode");
        }
        //位置判断
        if(switchAdCode.length() != 6){
            return Res.fail(BizExceptionEnum.RES_Ad_Code_Abnormal);
        }
        List<Map<String,Object>> advList = advMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzAdv>().like("screen_city",switchAdCode).eq("subtype", EnWzAdv.SUBTYPE_ADV.getIndex()).gt("end_time",new Date()).isNotNull("release_time").in("status",new Integer[]{5,6}).orderBy("release_time",false));
        for(Map<String,Object> advs:advList){
            Long advId = Long.parseLong(advs.get("advId").toString());
            List<WzAdvShare> advShareList = advShareMapper.selectList(new EntityWrapper<WzAdvShare>().eq("adv_id",advId).eq("user_code",userCode));
            if(advShareList.size() > 0){
                if(advShareList.get(0).getShareReward() != 0){
                    advs.put("isShare",1);
                }else{
                    advs.put("isShare",0);
                }
                advs.put("effectivecClicks",advShareList.get(0).getShareNumber());//有效点击数
                advs.put("myPartitionReward",0);//不参与瓜分
            }else{
                advs.put("isShare", 0);
                advs.put("effectivecClicks",0);//有效点击数
                advs.put("myPartitionReward",0);//是否参与瓜分
            }
            List<WzAdvShare> advShares = new ArrayList<>();
            List<Map<String, Object>> totalProfit = new ArrayList<>();
            if(advs.get("shareAverageReward").toString().equals("0")){
                advShares = advShareMapper.selectList(new EntityWrapper<WzAdvShare>().eq("adv_id",advId));
                totalProfit = advShareMapper.selectMaps(Condition.create().setSqlSelect("sum(share_number) As totalshareNumber").eq("adv_id",advId));
            }else{
                advShares = advShareMapper.selectList(new EntityWrapper<WzAdvShare>().eq("adv_id",advId).ne("share_reward",0));
                totalProfit = advShareMapper.selectMaps(Condition.create().setSqlSelect("sum(share_number) As totalshareNumber").eq("adv_id",advId).ne("share_reward",0));
            }
            advs.put("shareNumber",advShares.size());//参与分享人数
            if(totalProfit.get(0) == null){
                advs.put("totalshareNumber",0);//总点击数
            }else{
                advs.put("totalshareNumber",totalProfit.get(0).get("totalshareNumber").toString());//总点击数
            }
            //分享总人数
            int shareUserNumber = 0;
            if(Integer.parseInt(advs.get("shareAverageReward").toString()) != 0){
                shareUserNumber = Integer.parseInt(advs.get("shareReward").toString())/Integer.parseInt(advs.get("shareAverageReward").toString());
            }
            advs.put("shareUserNumber",shareUserNumber);
            //瓜分金额
            advs.put("partitionNumber",0);
            advs.put("partitionReward",advs.get("surplusReward"));
        }
        //新分享
//        String today = DateUtil.toString(new Date());
//        Date day = DateUtil.toDateTime(today + " 00:00:00");
//        List<WzAdv> advs = advMapper.selectList(new EntityWrapper<WzAdv>().in("status",new Integer[]{5,6}).ne("share_reward",0).ge("release_time",day));
//        int x = advs.size();
//        int myAdvShareCount = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().ge("status", EnWzAdv.STATUS_RELEASE_no.getIndex()).eq("user_code",userCode).ge("create_time",day));
//        x = x - myAdvShareCount;
//        WzUser user = cacheService.user(userCode);
//        if(user.getHasNewshare() != x){
//            user.setHasNewshare(x);
//            userMapper.updateById(user);
//        }
        return Res.success(paramMap.data(advList));
    }

    /**
     * 已完成分享广告列表
     */
    @PostMapping("advSharedList")
    public Res advSharedList(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        List<Map<String,Object>> advList = advShareMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzAdvShare>().eq("status", EnWzAdv.STATUS_Settlement.getIndex()).eq("user_code",userCode).orderBy("end_time",false));

        return Res.success(paramMap.data(advList));
    }

    /**
     * 分享广告成功调用
     */
    @PostMapping("advShareSuccess")
    public Res advShareSuccess(@RequestBody ParamMap paramMap){
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        Long advId = paramMap.getLongMisValid("advId");
        WzAdv adv = advMapper.selectById(advId);
        int c = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("adv_id",advId).eq("share_reward",-1));
        if(adv.getShareAverageReward() != 0){
            int m = adv.getShareReward()/adv.getShareAverageReward();
            if(c >= m){
                int r = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("user_code",userCode).eq("adv_id",advId).eq("share_reward",-1));
                if(r <= 0){
                    return Res.fail("分享人数已满!");
                }
            }
        }
        List<WzAdvShare> advShares = advShareMapper.selectList(new EntityWrapper<WzAdvShare>().eq("user_code",userCode).eq("adv_id",advId));
        if(advShares.size() <= 0 && adv.getEndTime().after(new Date())){
            WzAdvShare advShare = new WzAdvShare();
            advShare.setCreateTime(new Date());
            advShare.setUserCode(userCode);
            advShare.setAdvId(advId);
            advShare.setShareNumber(0);
            advShare.setCoverUrl(adv.getCoverUrl());
            advShare.setStatus(adv.getStatus());
            advShare.setClickNumber(1);
            advShare.setSubtype(adv.getSubtype());
            WzUser user = cacheService.user(userCode);
            advShare.setNickName(user.getNickName());
            advShare.setAvatarUrl(user.getAvatarUrl());
            advShare.setMobileType(user.getMobileType());
            advShare.setShareReward(-1);
            int r = advShareMapper.insert(advShare);
            if(r > 0){
                return Res.success();
            }else{
                return Res.fail();
            }
        }
        if(advShares.size() > 0 && adv.getEndTime().after(new Date())){
            if(advShares.get(0).getShareReward() == 0){
                advShares.get(0).setShareReward(-1);
                int r = advShareMapper.updateById(advShares.get(0));
                if(r > 0){
                    return Res.success();
                }else{
                    return Res.fail();
                }
            }
        }
        return Res.success();
    }

    /**
     * 广告主动失效
     */
    @PostMapping("advInvalid")
    public Res advInvalid(@RequestBody ParamMap paramMap){
        Long advUserId = paramMap.getLongMisValid("advUserId");
        int r = advUserMapper.deleteById(advUserId);
        if(r > 0){
            return Res.success();
        }
        return Res.fail();
    }


}

